package cn.edu.niit.studyspace.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.adapter.CourseAdapter;
import cn.edu.niit.studyspace.bean.Course;

public class CourseActivity extends AppCompatActivity {

  CourseAdapter adapter;

  private RecyclerView rcvCourse;
  List<Course> items;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course);

    initData();
    initView();
    initListener();
  }

  private void initView() {
    rcvCourse = findViewById(R.id.rcv_course);
    rcvCourse.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    adapter = new CourseAdapter(this, items);
    rcvCourse.setAdapter(adapter);
  }

  private void initData() {
    items = new ArrayList<>();
    items = DataSupport.findAll(Course.class, true);
  }

  private void initListener() {}

  @Override
  protected void onResume() {
    super.onResume();
    initData();
    adapter.notifyData(items);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_activity_course, menu);

    return true;
  }

  @Override
  public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case R.id.action_add_course:
        startActivity(new Intent(CourseActivity.this, NewCourseActivity.class));
        break;
    }

    return super.onOptionsItemSelected(item);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (adapter != null) {
      adapter = null;
    }
  }
}
